package Vista;


import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;


import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import Filtros.FiltroAmigo;
import Filtros.FiltroCurso;
import Filtros.FiltroDia;
import Filtros.FiltroHora;
import Filtros.FiltroSede;
import GestionDeDatos.GestorBD;
import GestionDeDatos.ResultadoConsulta;
import InfoCliente.UsuarioActivo;


public class Consultar {

private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private JTable table;

private static final String Filtro = "Filtro";
private static final String Tabla = "Tabla";

private JScrollPane scrollPane, jsp_amigos, jsp_materias, jsp_sede, jsp_dia, jsp_horario;
private JButton jb_consultar;
private JLabel jlb_intro, jlb_result;
private JCheckBox  jcb_materia, jcb_amigos, jcb_sede, jcb_dias, jcb_horario;
private Vector<String> jv_materias = new Vector<String>();
private Vector<String> jv_amigos = new Vector<String>();
private JList<String> jl_amigos, jl_materias, jl_sede, jl_dias, jl_horario;
	
	public Consultar() {
		initComponents();
	}

	protected void initComponents() {
		
		mainPanel.add(initSolapaFiltros(), Filtro);
	    mainPanel.add(initSolapaTable(), Tabla);
	    mainPanel.setSize(530, 450);
		
	    this.ConsultarFActionListener(new ActionListener() {
	         @Override
	         public void actionPerformed(ActionEvent e) {
	        	 
	           	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
	        	 ArrayList<FiltroCurso> materias = filtroMaterias();
	        	 ArrayList<FiltroAmigo> amigos = filtroAmigos();
	        	 ArrayList<FiltroSede> sedes = filtroSedes();
	        	 ArrayList<FiltroDia> dias = filtroDias();
	        	 ArrayList<FiltroHora> horas = filtroHoras();
	        	 
	        	 try {
	        		 ResultadoConsulta consulta  = GestorBD.Gestor().ConsultarPorFiltro(usuarioActivo, materias, amigos, sedes, dias, horas);
		        	 String data[][] = consulta.getRegisters();
		        	 String fields[] = consulta.getFields();
		        	 DefaultTableModel model = new DefaultTableModel(data, fields);
		        	 table.setModel(model);
	        	 } catch (Exception exception) {
	        		 
	        	 }

	        	 switchPanel(Tabla);
	         }
	      });

	}
	
	private  ArrayList<FiltroCurso>filtroMaterias() {
//   	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
   	 ArrayList<FiltroCurso> materias = new ArrayList<FiltroCurso>();
   		
   		if ((getJCheckBMateria().isSelected() == true) && 
   				(getJListMaterias().getSelectedIndices().length > 0)) {

   			String[] vector = getJListMaterias().getSelectedValuesList().toArray(new String[0]);
   			JList<String> list = new JList<String>(vector);
   		 
   			for (int i=0; i < list.getModel().getSize(); i++) {
   				String parts[] = list.getModel().getElementAt(i).split(" - ");
   				int depto = Integer.parseInt(parts[0]) / 100;
   				int codigo = Integer.parseInt(parts[0]);
   				String curso = parts[2];
   				materias.add(new FiltroCurso(depto, codigo, curso));
   			} 
   			
   			return materias;
   		 
   		}
   		return materias;
/*   		
   		 String[] fields = {"codigoMateria", "curso"};
   		 String[][] data = {};
	     String[][] elements = {};
	     Set<String[]> set = new HashSet<String[]>();

   		 try {
   			 data = GestorBD.Gestor().ObtenerInscripciones(usuarioActivo).getRegisters(fields);
   			 for (int k=0; k<data.length; k++) {
	        		 set.add(data[k]);
       		 }

       		 elements = set.toArray(new String[0][0]);
	         for (int i=0; i<elements.length; i++) {

	        	int depto = Integer.parseInt(elements[i][0])/100;
	        	int materia = Integer.parseInt(elements[i][0]);
	        	String curso = elements[i][1];
       			materias.add(new FiltroCurso(depto, materia, curso));
       		 }
       		 
   		 	} catch (Exception exception) {
       		 
   		 	}

   	 return materias;
*/
	}
	
	private  ArrayList<FiltroAmigo>filtroAmigos() {
	   	 UsuarioActivo usuarioActivo = new UsuarioActivo(View.id, View.pass);
	   	 ArrayList<FiltroAmigo> amigos = new ArrayList<FiltroAmigo>();

	   	 if ((getJCheckBAmigos().isSelected() == true) && 
	   			(getJListAmigos().getSelectedIndices().length > 0)) {
	
	   		String[] vector = getJListAmigos().getSelectedValuesList().toArray(new String[0]);
	   		JList<String> list = new JList<String>(vector);
	   		 
	   		 for (int i=0; i < list.getModel().getSize(); i++) {
	   			 
	   			 String parts[] = list.getModel().getElementAt(i).split(" - ");
	   			 int padron = Integer.parseInt(parts[0]);
	       		 amigos.add(new FiltroAmigo(padron));
	   		 } 
	   		 return amigos;

	   	 }

	   		 String[] fields = {"padron"};
	   		 String[][] data = {};
		     String[][] elements = {};
		     Set<String[]> set = new HashSet<String[]>();

	   		 try {
	   			 data = GestorBD.Gestor().ObtenerAmistades(usuarioActivo).getRegisters(fields);

	   			 for (int k=0; k<data.length; k++) {
		        	set.add(data[k]);
	       		 }

	       		 elements = set.toArray(new String[0][0]);
		         for (int i=0; i<elements.length; i++) {

		        	int padron = Integer.parseInt(elements[i][0]);
	       			amigos.add(new FiltroAmigo(padron));
	       		 }
	       		 
	   		 	} catch (Exception exception) {
	       		 
	       	 }

	   	 return amigos;

		}
	
	private  ArrayList<FiltroSede>filtroSedes() {
	   	 ArrayList<FiltroSede> sedes = new ArrayList<FiltroSede>();
	   	 
	   	 if ((getJCheckBSede().isSelected() == true) &&
	   			(getJListSede().getSelectedIndices().length > 0)) {
	   		 
	   		String[] vector = getJListSede().getSelectedValuesList().toArray(new String[0]);
	   		JList<String> list = new JList<String>(vector);
	   		 
	   		 for (int i=0; i < list.getModel().getSize(); i++) {
	   			 
	   			 if (list.getModel().getElementAt(i).equals("Paseo Colon")) sedes.add(new FiltroSede("PC"));
	   			 if (list.getModel().getElementAt(i).equals("Las Heras")) sedes.add(new FiltroSede("LH"));
	   			 if (list.getModel().getElementAt(i).equals("Ciudad Universitaria")) sedes.add(new FiltroSede("CU"));
	   		 } 
	   		 return sedes;

	   	 }
	       	
	   	sedes.add(new FiltroSede("PC"));
	   	sedes.add(new FiltroSede("LH"));
	   	sedes.add(new FiltroSede("CU"));

	   	return sedes;

		}
	
	private  ArrayList<FiltroDia>filtroDias() {
	   	 ArrayList<FiltroDia> dias = new ArrayList<FiltroDia>();
	   	 
	   	 if ((getJCheckBDias().isSelected() == true) &&
	   			(getJListDias().getSelectedIndices().length > 0)) {
	   		 
	   		String[] vector = getJListDias().getSelectedValuesList().toArray(new String[0]);
	   		JList<String> list = new JList<String>(vector);
	   		 
	   		 for (int i=0; i < list.getModel().getSize(); i++) {
	   			 
	   			 if (list.getModel().getElementAt(i).equals("Lunes")) dias.add(new FiltroDia("lunes"));
	   			 if (list.getModel().getElementAt(i).equals("Martes")) dias.add(new FiltroDia("martes"));
	   			 if (list.getModel().getElementAt(i).equals("Miercoles")) dias.add(new FiltroDia("miercoles"));
	   			 if (list.getModel().getElementAt(i).equals("Jueves")) dias.add(new FiltroDia("jueves"));
	   			 if (list.getModel().getElementAt(i).equals("Viernes")) dias.add(new FiltroDia("viernes"));
	   			 if (list.getModel().getElementAt(i).equals("Sabado")) dias.add(new FiltroDia("sabado"));
	   		 }
	   		 return dias;

	   	 }
	       	
	   		dias.add(new FiltroDia("lunes"));
	   		dias.add(new FiltroDia("martes"));
	   		dias.add(new FiltroDia("miercoles"));
	   		dias.add(new FiltroDia("jueves"));
	   		dias.add(new FiltroDia("viernes"));
	   		dias.add(new FiltroDia("sabado"));

	   	 return dias;
	}
	
	private  ArrayList<FiltroHora>filtroHoras() {
	   	 ArrayList<FiltroHora> horas = new ArrayList<FiltroHora>();
	   	 
	   	 if ((getJCheckBHorario().isSelected() == true) &&
	   			(getJListHorario().getSelectedIndices().length > 0)) {
	   		 
	   		String[] vector = getJListHorario().getSelectedValuesList().toArray(new String[0]);
	   		JList<String> list = new JList<String>(vector);
	   	 for (int i=0; i < list.getModel().getSize(); i++) {
   			 
   			 String parts[] = list.getModel().getElementAt(i).split(" - ");
       		 horas.add(new FiltroHora(parts[0], parts[1]));

   		 } 
	   	 return horas;


	   	 }

	   		for (int i=0; i < getJListHorario().getModel().getSize(); i++) {
	   			String parts[] = getJListHorario().getModel().getElementAt(i).split(" - ");
	   			horas.add(new FiltroHora(parts[0], parts[1]));
	   		}
	   		
	   	 return horas;
	}
	

	public void switchPanel(String key) {
		cardlayout.show(mainPanel, key);
	}
	
	protected JPanel initSolapaTable() {
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.add(getJLabelResult());
		panel.add(getResultTable());
		panel.setSize(530, 450);
		return panel;
	}
	
	protected JPanel initSolapaFiltros() {
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.add(getJLabelIntro());
		panel.add(getJButtonConsultar());
		panel.add(getJCheckBAmigos());
		panel.add(getJCheckBMateria());
		panel.add(getJCheckBDias());
		panel.add(getJCheckBSede());
		panel.add(getJCheckBHorario());
		
		panel.add( getAmigosScroll());
		panel.add( getMateriasScroll());
		panel.add( getSedeScroll());
		panel.add( getDiasScroll());
		panel.add( getHorarioScroll());
		panel.setSize(530, 450);
		return panel;
		
	}

	private void ConsultarFActionListener(ActionListener listener) {
		jb_consultar.addActionListener(listener);
	}
	
	private JCheckBox getJCheckBAmigos() {
		if (jcb_amigos == null) {
			jcb_amigos = new JCheckBox("Amigos");
			jcb_amigos.setBounds(50,100, 100, 25);
		}
		return jcb_amigos;
	}
	
	private JCheckBox getJCheckBMateria() {
		if (jcb_materia == null) {
			jcb_materia = new JCheckBox("Materias");
			jcb_materia.setBounds(50,170, 100, 25);
		}
		return jcb_materia;
	}
	
	private JCheckBox getJCheckBDias() {
		if (jcb_dias == null) {
			jcb_dias = new JCheckBox("Dias");
			jcb_dias.setBounds(50,240, 100, 25);
		}
		return jcb_dias;
	}
	
	private JCheckBox getJCheckBSede() {
		if (jcb_sede == null) {
			jcb_sede = new JCheckBox("Sedes");
			jcb_sede.setBounds(50,310, 100, 25);
		}
		return jcb_sede;
	}
	
	private JCheckBox getJCheckBHorario() {
		if (jcb_horario == null) {
			jcb_horario = new JCheckBox("Horarios");
			jcb_horario.setBounds(50,340, 100, 25);
		}
		return jcb_horario;
	}
	
	
	protected Vector<String> getVectorMaterias() {
		return jv_materias;
	}
	
	protected Vector<String> getVectorAmigos() {
		return jv_amigos;
	}
	
	protected JList<String> getJListAmigos() {
		if (jl_amigos == null) {
			jl_amigos = new JList<String>(jv_amigos);
			jl_amigos.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jl_amigos.setBounds(170,100,300,65);
			
			jl_amigos.setSelectionModel(new DefaultListSelectionModel() {
				private static final long serialVersionUID = 1L;

				public void setSelectionInterval(int index0, int index1) {
			        if(super.isSelectedIndex(index0)) {
			            super.removeSelectionInterval(index0, index1);
			        }
			        else {
			            super.addSelectionInterval(index0, index1);
			        }
			    }
			});
		}
		return jl_amigos;
	}
	
	protected JScrollPane getAmigosScroll() {
		if (jsp_amigos == null) {
			jsp_amigos = new JScrollPane();
			jsp_amigos.setBounds(170,100,300,65);
			jsp_amigos.getViewport().setView(getJListAmigos());
		}
		
		return jsp_amigos;
	}
	
	protected JList<String> getJListMaterias() {
		
		if (jl_materias == null) {
			jl_materias = new JList<String>(jv_materias);
			jl_materias.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jl_materias.setBounds(170,170,300,65); 
			
			jl_materias.setSelectionModel(new DefaultListSelectionModel() {
				private static final long serialVersionUID = 1L;

				public void setSelectionInterval(int index0, int index1) {
			        if(super.isSelectedIndex(index0)) {
			            super.removeSelectionInterval(index0, index1);
			        }
			        else {
			            super.addSelectionInterval(index0, index1);
			        }
			    }
			});
			
		}
		return jl_materias;
	}
	
	protected JScrollPane getMateriasScroll() {
			
		if (jsp_materias == null) {
			jsp_materias = new JScrollPane();
			jsp_materias.setBounds(170,170,300,65);
			jsp_materias.getViewport().setView(getJListMaterias());
		}
		
		return jsp_materias;
			
		}
	
	private JList<String> getJListDias() {
		if (jl_dias == null) {
			String menuItems[] = {"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado" };
			jl_dias = new JList<String>(menuItems);
			jl_dias.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jl_dias.setBounds(170,240,300,65);
			jl_dias.setSelectionModel(new DefaultListSelectionModel() {

			    /**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				public void setSelectionInterval(int index0, int index1) {
			        if(super.isSelectedIndex(index0)) {
			            super.removeSelectionInterval(index0, index1);
			        }
			        else {
			            super.addSelectionInterval(index0, index1);
			        }
			    }
			});
		}
		return jl_dias;
	}
	
	protected JScrollPane getDiasScroll() {
		if (jsp_dia == null) {
			jsp_dia = new JScrollPane();
			jsp_dia.setBounds(170,240,300,65);
			jsp_dia.getViewport().setView(getJListDias());
		}
		
		return jsp_dia;
	}
	
	private JList<String> getJListSede() {
		if (jl_sede == null) {
			String menuItems[] = {"Paseo Colon", "Las Heras", "Ciudad Universitaria" };
			jl_sede = new JList<String>(menuItems);
			jl_sede.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jl_sede.setBounds(170,310,300,50);
			
			jl_sede.setSelectionModel(new DefaultListSelectionModel() {

			    /**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				public void setSelectionInterval(int index0, int index1) {
			        if(super.isSelectedIndex(index0)) {
			            super.removeSelectionInterval(index0, index1);
			        }
			        else {
			            super.addSelectionInterval(index0, index1);
			        }
			    }
			});
		}
		return jl_sede;
	}
	
	private JScrollPane getSedeScroll() {
		if (jsp_sede == null) {
			jsp_sede = new JScrollPane();
			jsp_sede.setBounds(170,310,300,20);
			jsp_sede.getViewport().setView(getJListSede());
		}
		
		return jsp_sede;
	}
	
	private JList<String> getJListHorario() {
		if (jl_horario == null) {
			String menuItems[] = {"7:00 - 8:00", "8:00 - 9:00", "9:00 - 10:00", "10:00 - 11:00",
								  "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 15:00", "15:00 - 16:00",
								  "16:00 - 17:00", "17:00 - 18:00", "18:00 - 19:00", "19:00 - 20:00", "20:00 - 21:00",
								  "21:00 - 22:00", "22:00 - 23:00"};
			jl_horario = new JList<String>(menuItems);
			jl_horario.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			jl_horario.setBounds(170,340,300,65);
			
			jl_horario.setSelectionModel(new DefaultListSelectionModel() {

			    /**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				public void setSelectionInterval(int index0, int index1) {
			        if(super.isSelectedIndex(index0)) {
			            super.removeSelectionInterval(index0, index1);
			        }
			        else {
			            super.addSelectionInterval(index0, index1);
			        }
			    }
			});
		}
		return jl_horario;
	}
	
	private JScrollPane getHorarioScroll() {
		if (jsp_horario == null) {
			jsp_horario = new JScrollPane();
			jsp_horario.setBounds(170,340,200,65);
			jsp_horario.getViewport().setView(getJListHorario());
		}
		
		return jsp_horario;
	}

	private JButton getJButtonConsultar() {
		if (jb_consultar== null) {
			jb_consultar = new JButton();
			jb_consultar.setText("Consultar");
	        jb_consultar.setMargin(new Insets(1, 5, 1, 5));
	        jb_consultar.setBounds(400, 380, 100, 40); 
		}
		return jb_consultar;
	}
	
	private JLabel getJLabelResult() {
		if (jlb_result == null) {
			jlb_result = new JLabel("Resultados");
			Font newTextFieldFont=new Font(jlb_result.getFont().getName(),jlb_result.getFont().getStyle(),18);   
		    jlb_result.setFont(newTextFieldFont);  
		    jlb_result.setBounds(50, 20, 400, 50);
		}

		return jlb_result;
	}

	private JLabel getJLabelIntro() {
		if (jlb_intro == null) {
			jlb_intro = new JLabel("Filtros");
			Font newTextFieldFont=new Font(jlb_intro.getFont().getName(),jlb_intro.getFont().getStyle(),18);   
		    jlb_intro.setFont(newTextFieldFont);  
		    jlb_intro.setBounds(50, 20, 400, 50);
		}

		return jlb_intro;
	}
	
	private JScrollPane getResultTable() {
		
				  table = new JTable();
				  JTableHeader header = table.getTableHeader();
				  header.setBackground(Color.yellow);
				  scrollPane = new JScrollPane(table);
				  table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
				  scrollPane.setBounds(0,70,530, 380);
				  
				  return scrollPane;
	}
	
	
	protected void clearCheckBox() {
		jcb_amigos.setSelected(false);
		jsp_amigos.setOpaque(false);
		jcb_sede.setSelected(false);
		jcb_dias.setSelected(false);
		jcb_materia.setSelected(false);
		jcb_horario.setSelected(false);
	}
	
	public JComponent getMainComponent() {
	      return mainPanel;
	}
}

